package com.yuanduo_app.widget

import android.Manifest
import android.animation.ObjectAnimator
import android.app.Activity
import android.content.ContentValues
import android.content.Context
import android.graphics.*
import android.hardware.Camera
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.os.Handler
import android.os.Message
import android.provider.MediaStore
import android.util.AttributeSet
import android.util.Log
import android.view.SurfaceHolder
import android.view.View
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.ImageProxy
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.MyLocationStyle
import com.xujl.fastlib.utils.DateUtil
import com.xujl.fastlib.utils.JsonUtil
import com.xujl.fastlib.utils.ToastUtils
import com.yuanduo_app.MainActivityControl
import com.yuanduo_app.R
import com.yuanduo_app.bridge.DataModule
import com.yuanduo_app.consts.RNEvent
import com.yuanduo_app.db.waterdb.WaterData
import com.yuanduo_app.event.PermissionsEvent
import com.yuanduo_app.manager.RNModuleManager
import com.yuanduo_app.screenWidth
import com.yuanduo_app.utils.CameraUtil
import com.yuanduo_app.utils.SingleMediaScanner
import kotlinx.android.synthetic.main.view_water_camera2.view.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import pub.devrel.easypermissions.EasyPermissions
import pub.devrel.easypermissions.PermissionRequest
import java.io.File
import java.io.FileOutputStream
import java.io.IOException


/**
 * versions:
 * coding by pmj on 2021/7/26
 * desc: 水印相机实现
 */
class WaterCameraView : FrameLayout, LifecycleObserver, AMapLocationListener {

    /**
     * 定位
     */
    val mlocationClient: AMapLocationClient by lazy { AMapLocationClient(context) }

    //初始化定位参数
    var mLocationOption = AMapLocationClientOption()

    private lateinit var mSurfaceHolder: SurfaceHolder
    private var camera: Camera? = null //摄像头管理器

    /**
     * 是否是后置相机
     */
    var isCameraBack = true

    /**
     * 是否显示地图
     */
    var isShowMap = true;

    /**
     * 是否初始化相机和地图
     */
    var isInitMapAndCamera = false


    var permissions: Array<String> = arrayOf(
        Manifest.permission.CAMERA,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.ACCESS_COARSE_LOCATION
    )

    var timeHandler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            changeTime()

            if (!isInitMapAndCamera && EasyPermissions.hasPermissions(context, *permissions)) {
                initMapAndCamera()
            }

        }
    }


    @JvmOverloads
    constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        inflate(context, R.layout.view_water_camera2, this)
        init()

    }

    private fun init() {
        (context as AppCompatActivity).lifecycle.addObserver(this)

        EventBus.getDefault().register(this)

        requestPermission()


        mapview.onCreate(null)
        initView()

    }

    /**
     * 请求权限
     */
    private fun requestPermission() {
//        var request = PermissionRequest.Builder(
//            context as Activity,
//            100,
//            *permissions
//        ).build()
//        EasyPermissions.requestPermissions(request)
        var activity = context as MainActivityControl
        activity.requestRuntimePermissions(permissions)

    }


    private fun initView() {
        cameraBtn.setOnClickListener { gotoCameraBtnClick() }
        cancelBtn.setOnClickListener { gotoCancelBtnClick() }
        sureBtn.setOnClickListener { gotoSureBtnClick() }
        ll_camera_change.setOnClickListener { changeCamera() }
        historyBtn.setOnClickListener { historyInfo() }
        exitBtn.setOnClickListener { finish() }

        //关闭地图
        tv_close_map.setOnClickListener { changeMapView(false) }

        //打开地图
        imgv_map_small.setOnClickListener { changeMapView(true) }

        //放大地图
        tv_big.setOnClickListener {
            Log.i("tmgj", "放大")
            mapview.map.animateCamera(CameraUpdateFactory.zoomIn())
        }
        //缩小地图
        tv_small.setOnClickListener {
            Log.i("tmgj", "缩小")
            mapview.map.animateCamera(CameraUpdateFactory.zoomOut())
        }


        cbox_flash.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) cbox_flash.text = "开启" else cbox_flash.text = "关闭"
            var params = camera?.parameters
            params?.flashMode =
                if (cbox_flash.isChecked) Camera.Parameters.FLASH_MODE_ON else Camera.Parameters.FLASH_MODE_OFF
//            ToastUtils.toast("设置闪光灯")
            camera?.parameters = params
        }

        initSurface()

        if (EasyPermissions.hasPermissions(context, *permissions)) {
            initMapAndCamera()
        }
        cameraBtn.startAnimator()

        edit_car_num.maxWidth = (context.screenWidth * 0.5).toInt()
        changeTime()

        var mapParams = cl_map.layoutParams
        mapParams.width = (context.screenWidth * 0.38).toInt()
        mapParams.height = (context.screenWidth * 0.38 * 1.15).toInt()
        cl_map.layoutParams = mapParams


        var imgvMapParams = imgv_map.layoutParams
        imgvMapParams.width = (context.screenWidth * 0.38).toInt()
        imgvMapParams.height = (context.screenWidth * 0.38 * 1.15).toInt()
        imgv_map.layoutParams = imgvMapParams


    }

    var isReashTime = true
    private fun changeTime() {
        if (isReashTime) {
            tv_time?.text = DateUtil.getCurDate("yyyy年MM月dd日    HH:mm:ss")
        }
        timeHandler.sendEmptyMessageDelayed(0, 1000)
    }

    /**
     * 修改地图显示
     */
    private fun changeMapView(isShow: Boolean) {
        isShowMap = isShow
        if (isShow) {
            mapview.visibility = View.VISIBLE
            tv_big.visibility = View.VISIBLE
            tv_small.visibility = View.VISIBLE
            tv_close_map.visibility = View.VISIBLE
            imgv_map_small.visibility = View.GONE
        } else {
            mapview.visibility = View.GONE
            tv_big.visibility = View.GONE
            tv_small.visibility = View.GONE
            tv_close_map.visibility = View.GONE
            imgv_map_small.visibility = View.VISIBLE
        }
    }

    @Subscribe
    fun onPermissionsEvent(event: PermissionsEvent) {
        if (event.isSuccess && EasyPermissions.hasPermissions(context, *permissions)
        ) {
            initMapAndCamera()
        } else {
            requestPermission()
        }
    }

    private fun initMapAndCamera() {
        if (isInitMapAndCamera) {
            return
        }

        if (isCreatHolder) {
            setCamera()
        }
        initMapView()
        isInitMapAndCamera = true
    }

    fun setCarNum(carNum: String, lat: String? = "", lng: String? = "") {
        edit_car_num.setText(carNum)
        if (!carNum.isNullOrEmpty()) {
            edit_car_num.visibility = View.VISIBLE
        }

    }


    /**
     * 历史信息点击
     */
    fun historyInfo() {
        RNModuleManager
            .getInstance()
            .getModule(DataModule::class.java)
            .sendEvent("waterHistory", "")
    }


    /**
     * 退出相机
     */
    private fun finish() {
        onDestroy()
        RNModuleManager
            .getInstance()
            .getModule(DataModule::class.java)
            .sendEvent("waterFinish", "")

    }


    /**
     * 初始化地图
     */
    private fun initMapView() {
        val myLocationStyle: MyLocationStyle
        myLocationStyle =
            MyLocationStyle() //初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        myLocationStyle.interval(2000) //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW)
        myLocationStyle.showMyLocation(true)
        var aMap = mapview.map
        //不显示缩放按钮
        aMap.uiSettings.isZoomControlsEnabled = false
//        aMap.isMyLocationEnabled=true
        //设置缩放中心区域
        mapview.map.uiSettings.setZoomInByScreenCenter(true)
        aMap.myLocationStyle = myLocationStyle //设置定位蓝点的Style

        aMap.setOnMyLocationChangeListener {
//            Log.i("camera", "成功定位")
//            tv_address.text
        }
//aMap.getUiSettings().setMyLocationButtonEnabled(true);设置默认定位按钮是否显示，非必需设置。
//aMap.getUiSettings().setMyLocationButtonEnabled(true);设置默认定位按钮是否显示，非必需设置。
        aMap.isMyLocationEnabled = true // 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        initLocation()
    }

    private fun initLocation() {
        //设置定位监听
        mlocationClient.setLocationListener(this)
//设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy)
//设置定位间隔,单位毫秒,默认为2000ms
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000)
        mLocationOption.setOnceLocation(true)
//设置定位参数
        //设置定位参数
        mlocationClient.setLocationOption(mLocationOption)
        mlocationClient.startLocation()
    }

    var isCreatHolder = false
    private fun initSurface() {
        mSurfaceHolder = surface_view.holder
        mSurfaceHolder.setKeepScreenOn(true)
        mSurfaceHolder.addCallback(object : SurfaceHolder.Callback {
            override fun surfaceCreated(holder: SurfaceHolder) {
                isCreatHolder = true
                setCamera()
            }

            override fun surfaceChanged(
                holder: SurfaceHolder,
                format: Int,
                width: Int,
                height: Int
            ) {
//                setCamera()
            }

            override fun surfaceDestroyed(holder: SurfaceHolder) {
                releaseCamera()
            }
        })

    }

    //修改前后摄像头
    private fun changeCamera() {
        isCameraBack = !isCameraBack

        camera?.stopPreview()
        camera?.release()
        camera = null
//        if (isCameraBack) {
//            camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK)
//        } else {
//            camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT)
//        }

        var animation = ObjectAnimator.ofFloat(imgv_camera_change, "rotation", 0f, 360f)
        animation.duration = 200
        animation.start()

        setCamera()
    }

    /**
     * 初始化摄像头设置
     */
    private fun setCamera() {
        if (!EasyPermissions.hasPermissions(context, *permissions)) {
            return
        }
        post {
            if (camera == null) {
                if (isCameraBack) {
                    camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK)
                } else {
                    camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT)
                }
            }

            val parameters = camera?.parameters
            if (parameters?.supportedFocusModes?.contains(
                    Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE
                ) == true
            ) {
                parameters?.focusMode = Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE
            }

            //这里第三个参数为最小尺寸 getPropPreviewSize方法会对从最小尺寸开始升序排列 取出所有支持尺寸的最小尺寸

            //这里第三个参数为最小尺寸 getPropPreviewSize方法会对从最小尺寸开始升序排列 取出所有支持尺寸的最小尺寸
//        val previewSize =
//            CameraUtil.getInstance()
//                .getPropSizeForWidth(parameters?.supportedPreviewSizes, context.screenWidth)

//            val previewSize = changePreviewSize(camera, surface_view.width, surface_view.height)
            val previewSize = changePreviewSize(camera, surface_view.height, surface_view.width)
            previewSize?.let { parameters?.setPreviewSize(it.width, previewSize.height) }

//            val pictrueSize = changePicureSize(camera, surface_view.width, surface_view.height)
            val pictrueSize = changePicureSize(camera, surface_view.height, surface_view.width)
//            CameraUtil.getInstance().getPropSizeForHeight(parameters?.supportedPictureSizes, 800)
            pictrueSize?.let { parameters?.setPictureSize(it.width, pictrueSize.height) }
//        previewSize?.let { parameters?.setPictureSize(it.width, previewSize.height) }

            camera?.parameters = parameters


//        var cameraParams = cl_camera.layoutParams
//        cameraParams.width = context.screenWidth
//        cameraParams.height = (previewSize.width/previewSize.height.toFloat()*context.screenWidth).toInt()
//        cl_camera.layoutParams = cameraParams

//        changePreviewSize(camera,surface_view.width,surface_view.height)


//        var picHeight = context.screenWidth * pictrueSize.width / pictrueSize.height
//


            var cameraId =
                if (isCameraBack) Camera.CameraInfo.CAMERA_FACING_BACK else Camera.CameraInfo.CAMERA_FACING_FRONT
            CameraUtil
                .getInstance()
                .setCameraDisplayOrientation(
                    context as Activity,
                    cameraId, camera
                );
            camera?.reconnect()
            camera?.setPreviewDisplay(surface_view.holder)
            camera?.startPreview()


        }
    }


    private fun gotoCancelBtnClick() {
        changeBtnShow(true)
    }


    /**
     * 是否拍照中
     */
    var isCameraing = false
    private fun gotoCameraBtnClick() {
        if (isCameraing) {
            return
        }
        isCameraing = true
        //设置闪光灯
        if (isCameraBack) { //后置摄像头，设置闪光灯
            var params = camera?.parameters
            params?.flashMode =
                if (cbox_flash.isChecked) Camera.Parameters.FLASH_MODE_ON else Camera.Parameters.FLASH_MODE_OFF
//            ToastUtils.toast("设置闪光灯")
            camera?.parameters = params
            camera?.reconnect()
        }
        camera?.takePicture(null, null, object : Camera.PictureCallback {
            override fun onPictureTaken(data: ByteArray?, camera: Camera?) {
                data?.let {

                    var cameraId =
                        if (isCameraBack) Camera.CameraInfo.CAMERA_FACING_BACK else Camera.CameraInfo.CAMERA_FACING_FRONT
                    var bitmap = BitmapFactory.decodeByteArray(it, 0, it.size)
                    //对图片进行方向旋转处理
                    var usebitmap =
                        CameraUtil.getInstance().setTakePicktrueOrientation(cameraId, bitmap)

                    post {
                        startKeepAnim()
                        imgv_pre.setImageBitmap(usebitmap)
                        imgv_pre.visibility = View.VISIBLE

//                        var waterBitmap = loadBitmapFromView(cl_camera)
//                        imgv_result.setImageBitmap(waterBitmap)


                    }
                }
                isCameraing = false
            }
        })
        //照片完成后进行地图绘制
//        creatMapImg()

    }

    /**
     * 开始遮挡动画
     */
    private fun startKeepAnim() {
        var animation = AlphaAnimation(0.5f, 1f)
        animation.repeatMode = Animation.REVERSE
        animation.repeatCount = 1
        animation.duration = 500
        animation.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationStart(animation: Animation?) {

            }

            override fun onAnimationEnd(animation: Animation?) {
                changeBtnShow(false)
            }

            override fun onAnimationRepeat(animation: Animation?) {
            }
        })

        view_white.visibility = View.VISIBLE
        view_white.startAnimation(animation)


    }

    /**
     *  创建地图图片
     */
    private fun creatMapImg() {
        if (!isShowMap) {
            return
        }
        mapview.map.getMapScreenShot(object : AMap.OnMapScreenShotListener {
            override fun onMapScreenShot(bitmap: Bitmap?) {
                bitmap?.let {
                    imgv_map.setImageBitmap(it)
                    imgv_map.visibility = View.VISIBLE
                }
            }

            override fun onMapScreenShot(p0: Bitmap?, p1: Int) {
                Log.i("waterCamera", "-----" + p1)
            }
        })

    }

    /**
     * 拍照后改变view显示
     */
    fun changeBtnShow(isCameraimg: Boolean) {
        if (isCameraimg) {
            isReashTime = true
            imgv_pre.visibility = View.INVISIBLE
            cameraBtn.visibility = View.VISIBLE
            sureBtn.visibility = View.INVISIBLE
            cancelBtn.visibility = View.INVISIBLE
            historyBtn.visibility = View.VISIBLE
            exitBtn.visibility = View.VISIBLE
//            imgv_map.visibility = View.GONE
            loading.visibility = View.INVISIBLE
            camera?.reconnect() //从新连接摄像头
            camera?.startPreview()


            // 拍照中显示外边框
//            edit_car_num.setBackgroundResource(R.drawable.shape_rect_white_dash)
        } else {
            isReashTime = false
//            imgv_map.visibility = View.VISIBLE
            imgv_pre.visibility = View.VISIBLE
            cameraBtn.visibility = View.INVISIBLE
            sureBtn.visibility = View.VISIBLE
            cancelBtn.visibility = View.VISIBLE
            historyBtn.visibility = View.INVISIBLE
            exitBtn.visibility = View.INVISIBLE
            view_white.visibility = View.GONE

            // 拍照后去掉外边框
//            edit_car_num.setBackgroundColor(Color.TRANSPARENT)
        }
    }

    /**
     * 切换显示布局，下面这个方法是用于中间弹出小窗口显示方式
     * @param isCameraimg 是否是拍照中
     */
//    fun changeBtnShow(isCameraimg: Boolean) {
//        if (isCameraimg) {
//            imgv_pre.visibility = View.INVISIBLE
//            cameraBtn.visibility = View.VISIBLE
//            sureBtn.visibility = View.INVISIBLE
//            cancelBtn.visibility = View.INVISIBLE
//            historyBtn.visibility = View.VISIBLE
//            exitBtn.visibility = View.VISIBLE
//            imgv_map.visibility = View.GONE
//            cl_result.visibility = View.GONE
//            camera?.reconnect() //从新连接摄像头
//            camera?.startPreview()
//        } else {
//            cl_result.visibility = View.VISIBLE
//            imgv_pre.visibility = View.INVISIBLE
//            cameraBtn.visibility = View.INVISIBLE
//            sureBtn.visibility = View.VISIBLE
//            cancelBtn.visibility = View.VISIBLE
//            historyBtn.visibility = View.INVISIBLE
//            exitBtn.visibility = View.INVISIBLE
//            view_white.visibility = View.GONE
//
//        }
//    }


    /**
     * 修改相机的预览尺寸，调用此方法就行
     *
     * @param camera     相机实例
     * @param viewWidth  预览的surfaceView的宽
     * @param viewHeight 预览的surfaceView的高
     */
    fun changePreviewSize(camera: Camera?, viewWidth: Int, viewHeight: Int): Camera.Size? {
        camera?.let {
            var parameters = it.parameters
            var sizeList = parameters.supportedPreviewSizes
            var closelySize: Camera.Size? = null
            sizeList.forEach {
                if (it.width == viewWidth && it.height == viewHeight) {
                    closelySize = it
                    return@forEach
                }
            }
            if (closelySize == null) {
                var reqRatio = viewWidth / viewHeight.toFloat()
                var curRatio: Float = 0f
                var deltaRatio: Float = 0f
                var deltaRatioMin: Float = Float.MAX_VALUE
                sizeList.forEach {
                    if (it.width >= context.screenWidth) {
                        curRatio = it.width / it.height.toFloat()
                        deltaRatio = Math.abs(reqRatio - curRatio)
                        if (deltaRatio < deltaRatioMin) {
                            deltaRatioMin = deltaRatio
                            closelySize = it
                        }

                    }
                }
            }
            return closelySize

        }
        return null
    }

    /**
     * 修改相机的预览尺寸，调用此方法就行
     *
     * @param camera     相机实例
     * @param viewWidth  预览的surfaceView的宽
     * @param viewHeight 预览的surfaceView的高
     */
    fun changePicureSize(camera: Camera?, viewWidth: Int, viewHeight: Int): Camera.Size? {
        camera?.let {
            var parameters = it.parameters
            var sizeList = parameters.supportedPictureSizes
            var closelySize: Camera.Size? = null
            sizeList.forEach {
                if (it.width == viewWidth && it.height == viewHeight) {
                    closelySize = it
                    return@forEach
                }
            }
            if (closelySize == null) {
                var reqRatio = viewWidth / viewHeight.toFloat()
                var curRatio: Float = 0f
                var deltaRatio: Float = 0f
                var deltaRatioMin: Float = Float.MAX_VALUE
                sizeList.forEach {
                    if (it.width >= context.screenWidth) {
                        curRatio = it.width / it.height.toFloat()
                        deltaRatio = Math.abs(reqRatio - curRatio)
                        if (deltaRatio < deltaRatioMin) {
                            deltaRatioMin = deltaRatio
                            closelySize = it
                        }

                    }
                }
            }
            return closelySize

        }
        return null
    }


    /**
     * 确定使用
     */
    private fun gotoSureBtnClick() {
        loading.show()
        //异步去生成合成图片
        Thread {
            var file = viewSaveToImage(cl_camera)
            Log.i("xmgj", "文件路径" + file?.path)

            var waterData = WaterData()
            waterData.carNum = edit_car_num.text.toString()
            file?.path?.let { waterData.filePath = "file://$it" }
            waterData.time = tv_time.text.toString()

            mlocation?.let {
                waterData.address = tv_address.text.toString()
                waterData.lat = it.latitude.toString()
                waterData.lng = it.longitude.toString()
            }

            post {
                RNModuleManager
                    .getInstance()
                    .getModule(DataModule::class.java)
//            .sendEvent("userWater", file?.path)
                    .sendEvent(RNEvent.USER_WATER_CAMERA, JsonUtil.toJson(waterData))
            }

        }.start()


    }


    /**
     * 相机数据转换成bitmap
     */
    private fun toBitmap(image: ImageProxy): Bitmap? {
        val byteBuffer = image.planes[0].buffer
        byteBuffer.rewind()
        val bytes = ByteArray(byteBuffer.capacity())
        byteBuffer[bytes]
        val clonedBytes = bytes.clone()
        return BitmapFactory.decodeByteArray(clonedBytes, 0, clonedBytes.size)
    }

    /**
     * 旋转bitmap
     */
    private fun rotateBitmap(bitmap: Bitmap, degree: Int): Bitmap {
        val matrix = Matrix()
        matrix.postRotate(degree.toFloat())
        val rotatedBitmap =
            Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
        bitmap.recycle()
        return rotatedBitmap
    }


    /**
     * 把控件转换成bitmap并保存到文件
     *
     * @param view
     * @return
     */
    fun viewSaveToImage(view: View): File? {
        view.isDrawingCacheEnabled = true
        view.drawingCacheQuality = View.DRAWING_CACHE_QUALITY_HIGH
        view.drawingCacheBackgroundColor = Color.WHITE

        // 把一个View转换成图片
        val cachebmp = loadBitmapFromView(view)
        val fos: FileOutputStream
        var imagePath = ""
        var file: File? = null
        try {

//            var fileDir =
//                File(context.filesDir.path + "/xmgj")
            var fileDir =
                File(context.externalMediaDirs[0].path + "/xmgj")
            if (!fileDir.exists()) fileDir.mkdirs()

            // SD卡根目录
            file =
                File(
                    fileDir,
                    "water" + System.currentTimeMillis() + ".png"
                )
            fos = FileOutputStream(file)
            imagePath = file.getAbsolutePath()
            cachebmp.compress(Bitmap.CompressFormat.PNG, 100, fos)
            fos.flush()
            fos.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        Log.i("waterCamera", "imagePath=$imagePath")
        view.destroyDrawingCache()

        file?.let {
            //安卓11更新相册
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                saveImageToGallery2(cachebmp, it)
            } else {

            }

        }

        //通知媒体更新
        SingleMediaScanner(context, imagePath, SingleMediaScanner.ScanListener { })
        return file
    }


    fun saveImageToGallery2(bitmap: Bitmap, file: File) {
        val values = ContentValues()
        values.put(
            MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES
                    + File.separator + "xmgj"
        ) //Environment.DIRECTORY_SCREENSHOTS:截图,图库中显示的文件夹名。"xmgj"
        values.put(MediaStore.MediaColumns.DISPLAY_NAME, file.name)
        values.put(MediaStore.MediaColumns.MIME_TYPE, "image/png")
        values.put(MediaStore.MediaColumns.DATE_ADDED, System.currentTimeMillis() / 1000)
        values.put(MediaStore.MediaColumns.DATE_MODIFIED, System.currentTimeMillis() / 1000)
        values.put(
            MediaStore.MediaColumns.DATE_EXPIRES,
            (System.currentTimeMillis() / 1000)
        )
        values.put(MediaStore.MediaColumns.IS_PENDING, 1)
        val resolver = context.contentResolver
        val uri: Uri? = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)

        uri?.let {
            try {
                // First, write the actual data for our screenshot
                resolver.openOutputStream(uri).use { out ->
                    if (!bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)) {
                        throw IOException("Failed to compress")
                    }
                }
                // Everything went well above, publish it!
                values.clear()
                values.put(MediaStore.MediaColumns.IS_PENDING, 0)
                values.putNull(MediaStore.MediaColumns.DATE_EXPIRES)
                resolver.update(uri, values, null, null)
            } catch (e: IOException) {
                resolver.delete(uri, null, null)
                Log.d("Exception", e.toString())
            }
        }
    }


    private fun loadBitmapFromView(v: View): Bitmap {
        val w = v.width
        val h = v.height
        val bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
        val c = Canvas(bmp)
        c.drawColor(Color.WHITE)
        /** 如果不设置canvas画布为白色，则生成透明  */
        v.layout(0, 0, w, h)
        v.draw(c)
        return bmp
    }


    /**
     * 释放相机资源
     */
    private fun releaseCamera() {
        camera?.let {
            it.setPreviewCallback(null)
            it.stopPreview()
            it.release()
            camera = null
        }
    }

    fun onDestroy() {
        EventBus.getDefault().unregister(this)
        timeHandler.removeMessages(0)
        cameraBtn.stopAnimator()
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mapview.onDestroy()
        mlocationClient?.let {
            it.unRegisterLocationListener(this)
            it.stopLocation()
        }
    }

    var isReume = false

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun onResume() {
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mapview.onResume()

        if (!EasyPermissions.hasPermissions(context, *permissions)) {
            return
        }

//        if (camera == null) {
//            if (isCameraBack) {
//                camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK)
//            } else {
//                camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT)
//            }
//
//            surface_view.holder?.let {
//                setCamera()
//            }
//        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun onPause() {
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mapview.onPause()
        releaseCamera()
    }


    var mlocation: AMapLocation? = null
    override fun onLocationChanged(location: AMapLocation?) {
        location?.let {
            Log.i("xmgj", "地图定位" + location.errorCode + "-----" + location.description)
            if (it.errorCode == 0) {
                mlocation = location
                post {
                    tv_address.text = it.address
                }
            } else {
                mlocationClient.startLocation()
            }

        }
    }


}